package com.ado.bazinga.core.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ado.bazinga.core.annotation.AdminLoginToken;
import com.ado.bazinga.core.annotation.ApiDesc;
import com.ado.bazinga.core.common.http.HttpResult;
import com.ado.bazinga.core.common.params.dto.AdminCreateParam;
import com.ado.bazinga.core.common.params.dto.AdminDto;
import com.ado.bazinga.core.common.params.dto.LoginBean;
import com.ado.bazinga.core.common.params.vo.AdminVO;
import com.ado.bazinga.core.common.params.vo.AdminVoTwo;
import com.ado.bazinga.core.dal.entity.Admin;
import com.ado.bazinga.core.dal.entity.Operation;
import com.ado.bazinga.core.dal.entity.Role;
import com.ado.bazinga.core.exception.BazingaException;
import com.ado.bazinga.core.service.AdminService;
import com.ado.bazinga.core.service.OperationService;
import com.ado.bazinga.core.service.OrderService;
import com.ado.bazinga.core.service.RoleService;
import com.ado.bazinga.core.utils.EncryptUtils;
import com.ado.bazinga.core.utils.JWTUtils;

/**
 *@author adonais
 *@date 2020年3月20日
 *@description AdminController.java  管理员控制器
**/
@RestController
@RequestMapping(value = "/api/admin")
public class AdminController {
	
	/**定义日志**/
	private final static Logger log = LoggerFactory.getLogger(AdminController.class) ;
	
	@Autowired
	@Qualifier(value = "adminService")
	private AdminService adminService ;
	@Autowired
	@Qualifier(value = "orderService")
	private OrderService orderService ;
	@Autowired
	@Qualifier(value = "roleService")
	private RoleService roleService ;
	@Autowired
	@Qualifier(value = "operationService")
	private OperationService operationService ;
	
	@ApiDesc(desc = "管理员登录接口")
	@PostMapping(value = "/login")
	public HttpResult adminLogin(@RequestBody LoginBean loginBean) {
		if (StringUtils.isEmpty(loginBean.getAccount())) {
			throw new BazingaException("用户不能为空");
		}
		if (StringUtils.isEmpty(loginBean.getPassword())) {
			throw new BazingaException("密码不能为空") ;
		}
		log.info("[{}]:" , loginBean.toString());
//		JSONObject jsonObject = new JSONObject() ;
		Admin admin = adminService.findByAccount(loginBean.getAccount()) ;
		if (admin == null) {
			return HttpResult.error("登录失败,用户不存在");
		} else {
			String pwd = EncryptUtils.decode(admin.getPassword()) ;
			if (!(pwd.equals(loginBean.getPassword()))) {
				return HttpResult.error("登录失败，密码错误");
			} else {
				String token = JWTUtils.getToken(admin);
				AdminVO adminVO = new AdminVO();
				Role role = new Role() ;
				role = roleService.findByRoleId(admin.getRoleId()) ;
//				adminVO.setRoleVO(roleVO);
				adminVO.setRole(role);
				List<String> operaList = new ArrayList<String>();
				if (StringUtils.isNotEmpty(role.getOperationId())) {
					String[] opeArr = role.getOperationId().split(",") ;
					if (opeArr.length > 0) {
						for (String str : opeArr) {
							operaList.add(str) ;
						}
					}
					List<Operation> opList = new ArrayList<Operation>() ;
				    if (operaList.size() > 0) {
				    	for (String str : operaList) {
				    		Operation operation = new Operation() ;
				    		operation = operationService.findById(str) ;
				    		opList.add(operation) ;
				    	}
				    }
					adminVO.setAccount(admin.getAccount());
					adminVO.setToken(token);
					adminVO.setOperationList(opList);
				}
				return HttpResult.ok(adminVO) ;
			}
		}
	}
	
	@ApiDesc(desc = "管理员信息更新接口")
	@AdminLoginToken
	@PostMapping(value = "/updateAdmin")
	public HttpResult updateAdmin(@RequestBody AdminDto adminDto) {
		if (StringUtils.isEmpty(adminDto.getId())) {
			throw new BazingaException("管理员用户id不能为空");
		}
		Admin admin = adminService.findById(adminDto.getId()) ;
		admin = assemblyAdmin(admin, adminDto) ;
		if (StringUtils.isNotEmpty(adminDto.getPassword())) {
			admin.setPassword(EncryptUtils.encode(adminDto.getPassword()));
		}
		boolean flag = adminService.updateAdmin(admin) ;
		if (flag) {
			return HttpResult.ok("管理员修改信息成功") ;
		}
		return HttpResult.error("管路员修改信息失败");
	}
	
	@ApiDesc(desc = "管理员新增接口")
	@AdminLoginToken
	@PostMapping(value = "/createAdmin")
	public HttpResult createAdmin(@RequestBody AdminCreateParam adminDto) {
		Admin admin = new Admin() ;
		if (StringUtils.isEmpty(adminDto.getAccount())) {
			throw new BazingaException("用户名不能为空");
		}
		if (StringUtils.isEmpty(adminDto.getPassword())) {
			admin.setPassword(EncryptUtils.encode("000000"));
		}
		admin.setPassword(EncryptUtils.encode(adminDto.getPassword()));
		admin.setAccount(adminDto.getAccount());
		admin.setRoleId(adminDto.getRoleId());
		boolean flag = adminService.createAdmin(admin);
		if (flag) {
			return HttpResult.ok("新增管理员用户成功") ;
		}
		return HttpResult.error("新增管理员用户失败");
	}
	
	private Admin assemblyAdmin(Admin admin , AdminDto adminDto) {
		try {
			BeanUtils.copyProperties(admin, adminDto);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return admin ;
	}
	
	@ApiDesc(desc = "获取所有管理员")
	@GetMapping(value = "/getAll")
	@AdminLoginToken
	public HttpResult getAll() {
		log.info("[{}]" , "<-------  getAll ------->");
		List<Admin> adminList = adminService.findAll() ;
		List<AdminVoTwo> adminVOs = new ArrayList<AdminVoTwo>() ;
		for (Admin admin : adminList) {
			AdminVoTwo adminVO = new AdminVoTwo() ;
			adminVO.setAccount(admin.getAccount());
			adminVO.setId(admin.getId().toString());
			Role role = roleService.findByRoleId(admin.getRoleId()) ;
			adminVO.setRoleName(role.getRoleName());
			List<String> operaList = new ArrayList<String>();
			if (StringUtils.isNotEmpty(role.getOperationId())) {
				String[] opeArr = role.getOperationId().split(",") ;
				if (opeArr.length > 0) {
					for (String str : opeArr) {
						operaList.add(str) ;
					}
				}
				List<Operation> opList = new ArrayList<Operation>() ;
			    if (operaList.size() > 0) {
			    	for (String str : operaList) {
			    		Operation operation = new Operation() ;
			    		operation = operationService.findById(str) ;
			    		opList.add(operation) ;
			    	}
			    }
			    adminVO.setOperationList(opList);
			}
			adminVOs.add(adminVO) ;
			
		}
		return HttpResult.ok(adminVOs) ;
	}
	
	@ApiDesc(desc = "按id查询admin")
	@GetMapping(value = "/getAdminById")
	public HttpResult getAdminById(String adminId) {
		if(StringUtils.isEmpty(adminId)) {
			throw new BazingaException("id不能为空") ;
		}
		Admin admin = adminService.findById(adminId) ;
		AdminVO adminVO = new AdminVO();
		Role role = new Role() ;
		role = roleService.findByRoleId(admin.getRoleId()) ;
//		adminVO.setRoleVO(roleVO);
		adminVO.setRole(role);
		List<String> operaList = new ArrayList<String>();
		if (StringUtils.isNotEmpty(role.getOperationId())) {
			String[] opeArr = role.getOperationId().split(",") ;
			if (opeArr.length > 0) {
				for (String str : opeArr) {
					operaList.add(str) ;
				}
			}
			List<Operation> opList = new ArrayList<Operation>() ;
		    if (operaList.size() > 0) {
		    	for (String str : operaList) {
		    		Operation operation = new Operation() ;
		    		operation = operationService.findById(str) ;
		    		opList.add(operation) ;
		    	}
		    }
			adminVO.setAccount(admin.getAccount());
			adminVO.setOperationList(opList);
		}
		return HttpResult.ok(adminVO) ;
	}
	
	@ApiDesc(desc = "删除管理员用户")
	@AdminLoginToken
	@PostMapping(value = "/deleteAdminById")
	public HttpResult deleteAdminById(String adminId) {
		if(StringUtils.isEmpty(adminId)) {
			throw new BazingaException("id不能为空") ;
		}
		boolean flag = adminService.deleteById(adminId) ;
		if(flag) {
			return HttpResult.ok("删除成功") ;
		}
		return HttpResult.error("删除失败");
	}
	
}
